package com.YOTO.httpstaticserver.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Controller
public class FileController {
    
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    private final String FILE_DIRECTORY = "upload-dir";

    @GetMapping("/")
    public String listFiles(Model model) {
        File dir = new File(FILE_DIRECTORY);
        File[] files = dir.listFiles();
        List<String> fileNames = new ArrayList<>();
        
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    fileNames.add(file.getName());
                }
            }
        }
        
        model.addAttribute("files", fileNames);
        return "index";
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file, HttpSession session) {
        if (session.getAttribute("isLoggedIn") == null) {
            return "redirect:/login";
        }
        
        if (file.isEmpty()) {
            return "redirect:/?error=empty";
        }

        try {
            String fileName = file.getOriginalFilename();
            Path targetPath = Paths.get(FILE_DIRECTORY).resolve(fileName);
            Files.copy(file.getInputStream(), targetPath);
            return "redirect:/?success=true";
        } catch (IOException e) {
            return "redirect:/?error=failed";
        }
    }

    @DeleteMapping("/files")
    @ResponseBody
    public ResponseEntity<String> deleteAllFiles(HttpSession session) {
        if (session.getAttribute("isLoggedIn") == null) {
            return ResponseEntity.status(401).body("未登录");
        }

        File dir = new File(FILE_DIRECTORY);
        if (!dir.exists()) {
            return ResponseEntity.notFound().build();
        }

        File[] files = dir.listFiles();
        if (files != null) {
            Arrays.stream(files)
                  .filter(File::isFile)
                  .forEach(File::delete);
            return ResponseEntity.ok("所有文件已删除");
        }
        
        return ResponseEntity.ok("文件夹为空");
    }
} 